package com.webside.front.detail.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.itextpdf.xmp.impl.Base64;
import com.webside.front.common.model.BSeries;
import com.webside.front.common.model.BVideo;
import com.webside.front.common.model.Bdictionary;
import com.webside.front.common.model.PBanner;
import com.webside.front.common.model.RComment;
import com.webside.front.common.model.VideoFromWeb;
import com.webside.front.common.service.BVideoFromWebService;
import com.webside.front.common.service.RCommentService;
import com.webside.front.detail.service.IDetailService;
import com.webside.front.detail.utils.CookiesUtil;
import com.webside.front.detail.utils.HttpUtil;
import com.webside.front.detail.utils.TokenUtils;
import com.webside.front.index.service.IndexService;
import com.webside.front.listener.BaseData;
import com.webside.mongo.model.MongoRecord;
import com.webside.util.Common;
import com.webside.util.SensitivewordFilter;

import jodd.util.URLDecoder;

@Controller
@Scope("prototype")
@RequestMapping(value="/public/detail/")
public class DetailController {
	@Autowired
	private	IDetailService detailService;
	@Autowired
	private RCommentService rCommentService; 
	@Autowired
	private BVideoFromWebService bVideoFromWebService; 
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private IndexService indexService;
	public static String vcBasePath="http://vc.sh.vnet.cn:8080/auth_service";
	@RequestMapping(method = RequestMethod.GET, value = "/playVideo")
	public void playVideo(HttpServletRequest request, HttpServletResponse response) throws IOException{
		// TODO Auto-generated method stub
		String appId="abefe3a4-27e4-11e6-9089-047d7becc";
		String appKey="c3477aff-27e4-11e6-9089-047d7becc1fa";
		String encodeType=TokenUtils.ENCRY_TYPE_AES;
		String accessKey=TokenUtils.encodeRequest(appId, appKey, encodeType);
		
		String requestUrl=null;
		JSONObject returnJson=HttpUtil.executeHttpPost(vcBasePath+"/auth?accessKey="+accessKey+"&decodeType="+encodeType, null, null, null, null);
		try {
			String token="";
			if(returnJson!=null){
			 token=(String)returnJson.getString("token");
			}
			String appInfo=TokenUtils.decodeResponse(token,encodeType);
			System.out.println(appInfo);
			String[] appInfoStrs=appInfo.split(TokenUtils.SPLIT_CHAR);
			
			String cdnToken=appInfoStrs[1];
			String resUrl=request.getParameter("res_url");
			String deResUrl=Base64.decode(resUrl);
			requestUrl=deResUrl+"&token="+cdnToken;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.sendRedirect("http://player.youku.com/player.php/Type/Folder/Fid//Ob//sid/XMTc4MTgzNTM4MA==/v.swf");
	}
	
	@RequestMapping("show.html")
	public String show(HttpServletRequest request, HttpServletResponse response,Model m,PBanner pbanner,@RequestParam("seriesId") Integer seriesId,@RequestParam("setNum") Integer setNum, Integer pageNo,String channel,String youkuId) throws Exception{
		//判断是否有优酷视频
		VideoFromWeb videoFromWeb = null;
		BSeries bSeries=null;
		if(youkuId!=null && seriesId==null && setNum==null){
			videoFromWeb=indexService.selectVideoById(Long.parseLong(youkuId));
			videoFromWeb.setPlayUrl(videoFromWeb.getPlayUrl().substring(videoFromWeb.getPlayUrl().indexOf("sid/")+4, videoFromWeb.getPlayUrl().indexOf("/v.swf")));
			m.addAttribute("youkuS",videoFromWeb.getPlayUrl());
			BSeries bSeries1=new BSeries();
			bSeries1.setTypeName("预告片");
			bSeries1.setId(Integer.parseInt(youkuId));
			bSeries1.setSummary(videoFromWeb.getDescription());
			m.addAttribute("bSeries",bSeries1);
		}else {
			bSeries= detailService.selectSeriesById(seriesId);
			m.addAttribute("bSeries",bSeries);
			
		}
		m.addAttribute("baseImgPath",BaseData.img_base_path);
		m.addAttribute("channel", channel);
		//简介
		List<Bdictionary> list=detailService.selectKeywords();
		String []keyarr=list.get(0).getName().split(",");
		m.addAttribute("bdictionaryKeywords_list",keyarr);
		//测试用hu
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = format.format(new Date());
		List<HashMap<String, Object>> BANNER7 = indexService.queryAdByAll(date, "BANNERSEVEN");
		List<HashMap<String, Object>> RECT3 = indexService.queryAdByAll(date, "RECTTHREE");
		if (BANNER7.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i <BANNER7.size(); i++) {

				AdRelease = "<a target='target' class='banner7' status='" + BANNER7.get(i).get("status") + "' interval='"
						+ BANNER7.get(i).get("ad_interval") + "' href='" + BANNER7.get(i).get("link_url")
						+ "'><img count='0' pcode='" + BANNER7.get(i).get("code") + "' pname='"
						+ BANNER7.get(i).get("name") + "' adid='" + BANNER7.get(i).get("id") + "' adtitle='"
						+ BANNER7.get(i).get("title") + "' adtypename='" + BANNER7.get(i).get("type_name")
						+ "' adtype='" + BANNER7.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='1200' height='100' src='"
						+ BANNER7.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			m.addAttribute("banner7_list",lists);
		}
		if (RECT3.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i <RECT3.size(); i++) {

				AdRelease = "<a target='target' class='rect3' status='" + RECT3.get(i).get("status") + "' interval='"
						+ RECT3.get(i).get("ad_interval") + "' href='" + RECT3.get(i).get("link_url")
						+ "'><img count='0' pcode='" + RECT3.get(i).get("code") + "' pname='"
						+ RECT3.get(i).get("name") + "' adid='" + RECT3.get(i).get("id") + "' adtitle='"
						+ RECT3.get(i).get("title") + "' adtypename='" + RECT3.get(i).get("type_name")
						+ "' adtype='" + RECT3.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='228' height='95' src='"
						+ RECT3.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			m.addAttribute("rect3_list",lists);
		}
		if(bSeries!=null){
			//剧集选择
			List<BVideo> bVideoList=detailService.selectVideoBySeriesId(bSeries.getId());
			m.addAttribute("bVideoList", bVideoList);
			BVideo bv=null;
			for(int i=0;i<bVideoList.size();i++){
				if( bVideoList.get(i).getSetNum()==setNum){
					bv=bVideoList.get(i);
					m.addAttribute("bVideo",bv);
					break;
				}
		}
			//播放次数
			Integer pCount=0;
			if(bv.getPlayCount()==null){
				pCount=1;
			}else{
				pCount=bv.getPlayCount()+1;
			}
			bv.setPlayCount(pCount);
			detailService.play(bv);
			//是否点赞
			Cookie cookie = CookiesUtil.getCookieByName(request, bv.getId()+"like");
			if(cookie != null  ){
				if("likeIt".equals(cookie.getValue())){
					m.addAttribute("like", "likeIt");
				}else{
					m.addAttribute("like", "It");
				}
				
			}else{
				m.addAttribute("like", "It");
			}
			//替换地址//
			String url=bv.getH720pUrl();
			url.replace("//", "\\\\");
			bv.setH720pUrl(url);
			//看过此片还喜欢
			BSeries conditionSeries=new BSeries();
			
			conditionSeries.setType(bSeries.getType());
			List<BSeries> mayLikeSeries=detailService.selectMayLike(bSeries);
			m.addAttribute("mayLikeSeriesList", mayLikeSeries);
			
			//排行推荐
			conditionSeries.setChannel(bSeries.getChannel());
			List<BSeries> mayChannelSeries=detailService.selectMayChannel(bSeries);
			m.addAttribute("mayChannelSeriesList", mayChannelSeries);
			//精彩片段
			List<VideoFromWeb> videoFromWebs=indexService.queryByBind(bv.getId(),0);
			m.addAttribute("Marvellous",videoFromWebs);
			
			//获得评论区分页参数
			int cPageSize;
			int c_Count=detailService.CommentCount(bv.getId());
			m.addAttribute("c_Count", c_Count);
			if(c_Count>7 ){
				cPageSize=c_Count/7;
				 if(c_Count%7==0){
						m.addAttribute("cPageSize",cPageSize);
					}else{
						m.addAttribute("cPageSize",cPageSize+1);
					}
			}else{
				cPageSize=0;
				m.addAttribute("cPageSize",cPageSize);
			}
			
			
			
		}else{
			List<BVideo> bVideoList=new ArrayList<BVideo>();
			
			BVideo bVideo1=new BVideo();
			bVideoList.add(bVideo1);
			m.addAttribute("youkuid",youkuId);
			m.addAttribute("bVideoList", bVideoList);
			bVideo1.setTag(videoFromWeb.getTitle());
			if(indexService.addPlayCount(videoFromWeb)>0){
				bVideo1.setPlayCount(videoFromWeb.getPlayCount()+1);
			};
			bVideo1.setLikeCount(videoFromWeb.getLikeCount());
			m.addAttribute("bVideo",bVideo1);
			//播放次数
			//看过此片还喜欢
			//排行推荐
			BSeries bSeries1=new BSeries();
			List<BSeries> mayLikeSeries=indexService.selectByPrimarySelective(bSeries);
			m.addAttribute("mayLikeSeriesList",mayLikeSeries);
			bSeries1.setChannel("MOVIE");
			List<BSeries> mayChannelSeries=detailService.selectMayChannel(bSeries1);
			m.addAttribute("mayChannelSeriesList", mayChannelSeries);
			//精彩片段
			List<VideoFromWeb> videoFromWebs=indexService.queryByBind(0,Integer.parseInt(youkuId));
			m.addAttribute("Marvellous",videoFromWebs);
			//获得评论区分页参数
			//获得评论区分页参数
			int cPageSize;
			int c_Count=detailService.CommentCount(Integer.parseInt(youkuId));
			m.addAttribute("c_Count", c_Count);
			if(c_Count>7 ){
				cPageSize=c_Count/7;
				 if(c_Count%7==0){
						m.addAttribute("cPageSize",cPageSize);
					}else{
						m.addAttribute("cPageSize",cPageSize+1);
					}
			}else{
				cPageSize=0;
				m.addAttribute("cPageSize",cPageSize);
			}
		}
		return Common.BACKGROUND_PATH + "/front/video";
		}
		
		
	@RequestMapping("shows.html")
	public String shows(HttpServletRequest request, HttpServletResponse response,Model m,PBanner pbanner,@RequestParam("seriesId") Integer seriesId,@RequestParam("setNum") Integer setNum, Integer pageNo,String channel,String youkuId) throws Exception{
		// 判断是否有优酷视频
		VideoFromWeb videoFromWeb = null;
		BSeries bSeries = null;
		if (youkuId != null && seriesId == null && setNum == null) {
			videoFromWeb = indexService.selectVideoById(Long.parseLong(youkuId));
			videoFromWeb.setPlayUrl(videoFromWeb.getPlayUrl().substring(videoFromWeb.getPlayUrl().indexOf("sid/") + 4,
					videoFromWeb.getPlayUrl().indexOf("/v.swf")));
			m.addAttribute("youkuS", videoFromWeb.getPlayUrl());
			BSeries bSeries1 = new BSeries();
			bSeries1.setTypeName(videoFromWeb.getTypeName());
			bSeries1.setId(Integer.parseInt(youkuId));
			bSeries1.setSummary(videoFromWeb.getDescription());
			m.addAttribute("bSeries", bSeries1);
		} else {
			bSeries = detailService.selectSeriesById(seriesId);
			m.addAttribute("bSeries", bSeries);

		}
		m.addAttribute("baseImgPath", BaseData.img_base_path);
		m.addAttribute("channel", channel);
		// 简介
		List<Bdictionary> list = detailService.selectKeywords();
		String[] keyarr = list.get(0).getName().split(",");
		m.addAttribute("bdictionaryKeywords_list", keyarr);
		// 测试用hu
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = format.format(new Date());
		List<HashMap<String, Object>> BANNER7 = indexService.queryAdByAll(date, "BANNERSEVEN");
		List<HashMap<String, Object>> RECT3 = indexService.queryAdByAll(date, "RECTTHREE");
		if (BANNER7.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i < BANNER7.size(); i++) {

				AdRelease = "<a target='target' class='banner7' status='" + BANNER7.get(i).get("status")
						+ "' interval='" + BANNER7.get(i).get("ad_interval") + "' href='"
						+ BANNER7.get(i).get("link_url") + "'><img count='0' pcode='" + BANNER7.get(i).get("code")
						+ "' pname='" + BANNER7.get(i).get("name") + "' adid='" + BANNER7.get(i).get("id")
						+ "' adtitle='" + BANNER7.get(i).get("title") + "' adtypename='"
						+ BANNER7.get(i).get("type_name") + "' adtype='" + BANNER7.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='1200' height='100' src='"
						+ BANNER7.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			m.addAttribute("banner7_list", lists);
		}
		if (RECT3.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i < RECT3.size(); i++) {

				AdRelease = "<a target='target' class='rect3' status='" + RECT3.get(i).get("status") + "' interval='"
						+ RECT3.get(i).get("ad_interval") + "' href='" + RECT3.get(i).get("link_url")
						+ "'><img count='0' pcode='" + RECT3.get(i).get("code") + "' pname='" + RECT3.get(i).get("name")
						+ "' adid='" + RECT3.get(i).get("id") + "' adtitle='" + RECT3.get(i).get("title")
						+ "' adtypename='" + RECT3.get(i).get("type_name") + "' adtype='" + RECT3.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='228' height='95' src='"
						+ RECT3.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			m.addAttribute("rect3_list", lists);
		}
		if(bSeries == null) {
			List<BVideo> bVideoList = new ArrayList<BVideo>();

			BVideo bVideo1 = new BVideo();
			bVideoList.add(bVideo1);
			m.addAttribute("youkuid", youkuId);
			m.addAttribute("bVideoList", bVideoList);
			bVideo1.setTag(videoFromWeb.getTitle());
			if (indexService.addPlayCount(videoFromWeb) > 0) {
				bVideo1.setPlayCount(videoFromWeb.getPlayCount() + 1);
			}
			;
			bVideo1.setLikeCount(videoFromWeb.getLikeCount());
			m.addAttribute("bVideo", bVideo1);
			// 播放次数
			// 看过此片还喜欢
			// 排行推荐
			BSeries bSeries1 = new BSeries();
			List<BSeries> mayLikeSeries = indexService.selectByPrimarySelective(bSeries);
			m.addAttribute("mayLikeSeriesList", mayLikeSeries);
			bSeries1.setChannel("MOVIE");
			List<BSeries> mayChannelSeries = detailService.selectMayChannel(bSeries1);
			m.addAttribute("mayChannelSeriesList", mayChannelSeries);
			// 精彩片段
			Map<String,Object> conditiona = new HashMap<String,Object>();
			conditiona.put("typeCode", videoFromWeb.getTypeCode());
			conditiona.put("status", "PUBLISHED");
			conditiona.put("pageSize", 10);
			conditiona.put("orderByColumn", "play_count");
			conditiona.put("orderByType", "DESC");
			List<VideoFromWeb> videoFromWebs = bVideoFromWebService.selectWebVideoByCondition(conditiona);//indexService.queryByBind(0, Integer.parseInt(youkuId));
			m.addAttribute("Marvellous", videoFromWebs);
			// 获得评论区分页参数
			// 获得评论区分页参数
			int cPageSize;
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("videoFromWebId", youkuId);
			condition.put("parentId", 0);
			condition.put("type", "2");
			int c_Count = rCommentService.selectCountByCondition(condition);
			System.out.println(c_Count+"父评论是这么多条");
			m.addAttribute("c_Count", c_Count);
			cPageSize = (int) Math.ceil((double)c_Count / 5);
			m.addAttribute("cPageSize", cPageSize);
		}
		return Common.BACKGROUND_PATH + "/front/detailpage/webVideoDetail";
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/addRecord.html")
	@ResponseBody
	public void getStatisticsRecord(MongoRecord mongoRecord,HttpServletRequest request) {
		try {
			
				// 调用java自带的uuid生成唯一标示id
				UUID uuid = UUID.randomUUID();
				// 去掉不需要的字符
				String id = uuid.toString().replaceAll("\\-", "");
				// 为实体对象加入标示id
				mongoRecord.setId(id);
				mongoRecord.setIp(Common.toIpAddr(request));
				mongoTemplate.insert(mongoRecord,"play_records");


		} catch (Exception e) {
			e.printStackTrace();


		}
		// 返回标示符


	
		
	}
	//获得父级评论
	@RequestMapping("recomment.html")
	@ResponseBody
	public Object showComment(@RequestParam("videoId") Integer videoId,@RequestParam("pageNo") Integer pageNo,HttpSession session,String youkuId) throws Exception{
		System.out.println(pageNo);
		long beginTime = System.currentTimeMillis();
		List<RComment> rCommentList=null;
		if(youkuId.trim().equals("")){
			rCommentList=detailService.selectRComment(videoId ,pageNo);
		}else {
			Map<String,Object>condition = new HashMap<String,Object>();
			System.out.println("youkuId:"+ youkuId);
			condition.put("seriesId", Integer.parseInt(youkuId));
			condition.put("pageNo", pageNo);
			rCommentList=detailService.selectInfoCommentByCondition(condition);
			System.out.println(rCommentList.size());
			System.out.println("来到这里了么==========================");
		}
		session.setAttribute("commentCount",rCommentList.size());
 		SensitivewordFilter filter=new SensitivewordFilter();
		for (int i = 0; i < rCommentList.size(); i++) {
			String content= filter.replaceSensitiveWord(rCommentList.get(i).getContent(), 1, "*");
			rCommentList.get(i).setContent(content);
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总共消耗时间为：" + (endTime - beginTime));
		JSONArray json1 = new JSONArray();
		json1.addAll(rCommentList);
		System.out.println(json1);
		if(json1.size()>0){
			return rCommentList;
		}
		String No_msg="";
		No_msg = "尚未评论";
		return json1;
	}
	//获得子级评论
	@RequestMapping("replyComment.html")
	@ResponseBody
	public Object showRComment(@RequestParam("videoId") Integer videoId,@RequestParam("pageNo") Integer pageNo,@RequestParam("parentId") Integer commentId,Model m) throws Exception{
		
		long beginTime = System.currentTimeMillis();
		List<RComment> rCommentList=detailService.selectReplyComment(videoId ,pageNo,commentId);
		 
		int r_Count=detailService.ReplyCount(commentId);
		int cPageSize_1=r_Count%7;
		if(r_Count%7==0){
			m.addAttribute("cPageSize_1",cPageSize_1);
		}else{
			m.addAttribute("cPageSize_1",cPageSize_1+1);
		}
		SensitivewordFilter filter=new SensitivewordFilter();
		for (int i = 0; i < rCommentList.size(); i++) {
			String content= filter.replaceSensitiveWord(rCommentList.get(i).getContent(), 1, "*");
			rCommentList.get(i).setContent(content);
		}
		long endTime = System.currentTimeMillis();
		System.out.println("总共消耗时间为：" + (endTime - beginTime));
		JSONArray json = new JSONArray();
		json.addAll(rCommentList);
		System.out.println(json);
		if(json.size()>0){
			return rCommentList;
		}else{
			if(pageNo!=0){
				return "加载完毕";
			}else{
				return "尚未回复评论";
			}
		}
	    /* String	msg ="尚未回复评论";
	     JSONObject j = JSONObject.fromObject(msg);
		return "尚未回复评论";*/
	}
	//获得视频信息
	@RequestMapping("videoMsg.html")
	@ResponseBody
	public Object showVideoMsg(@RequestParam("videoId") Integer videoId){
		BVideo video = detailService.showVideoMsg(videoId);
		if(video!=null)
			return video;
		String videoMsg="视频信息缺失";
		return videoMsg;
	}
	//点赞
	@RequestMapping("likeCount.html")
	@ResponseBody
	public Object likeCount(@RequestParam("videoId") Integer videoId,String youkuId,HttpServletRequest request, HttpServletResponse response){
		CookiesUtil.addCookie(response, videoId+"like", "likeIt", 30*24*3600);
		System.out.println("优酷Id:"+youkuId+"======================");
		if(youkuId.trim().equals("")){
			Integer likeVideo = detailService.like(videoId);
			return likeVideo;
			}else {
				System.out.println("准备插入点赞数据了====================");
				VideoFromWeb likecount=indexService.selectVideoById(Long.parseLong(youkuId));
				if(indexService.addLikeCount(likecount)>0){
					return likecount.getLikeCount()+1;
				}else {
					
					return likecount.getLikeCount();
				}
				
			}
	}
	//发表评论
	@RequestMapping("insertComment.html")
	@ResponseBody
	public Object insertComment(@RequestParam("videoId") Integer videoId,@RequestParam("parentId") Integer parentId,@RequestParam("content") String content,@RequestParam("childrenCount") String childrenCount){
		String c=URLDecoder.decode(content,"UTF-8");
		RComment comment=new RComment();
		comment.setVideoId(videoId);
		comment.setParentId(parentId);
		comment.setContent(c);
		if(childrenCount.equals("0") && childrenCount!=null){
			comment.setChildrenCount(1);
		}
		Date date=new Date();
		comment.setCreateTime(date);
		comment.setType("2");
		Object com = detailService.insertComment(comment);
		if(parentId!=0){
			detailService.addCount(comment);
		}
		
		if(comment!=null)
			return comment;
		return 0;
	}
	//资源集合
	/*@RequestMapping("EpisodeResouce.html")
	@ResponseBody
	public Object EpisodeResouce(@RequestParam("seriesId") Integer seriesId) throws Exception{
		List<RComment> rCommentList=detailService.selectVideo(seriesId );
		JSONArray json = new JSONArray();
		json.addAll(rCommentList);
		System.out.println(json);
		if(json.size()>0){
			return json;
		}
		String msg = "尚未回复评论";
		return msg;
	}
	*/
	//点赞
		@RequestMapping("test.html")
		public String test(){
			
			return  Common.BACKGROUND_PATH + "/front/test";
		}
		
}
